/*
 *  dataManager.js
 *
 *  This file has these main responsibilities:
 *  1. Initialize the main page, index.html.
 *  2. Setup all the listeners for the main page.
 *  3. Grab values of HTML elements for other parts of the application.
 *
 *  @author John Olennikov, Devin Helmgren
 */


define(['require','jquery', 'viewManager'], function(req, $, vm) 
{
    // Reference to the Google Map object
    var map;
    // Set the Google API key
    var apikey = 'AIzaSyAO_EMKk4DS8WlNxOjAHMnEqbevQvt1n7Y';
    // URL for less typing and errors
    var queryUrl= "https://www.googleapis.com/fusiontables/v1/query";
    // Fusion Table Id
    var fTableId = "1EcN_0nfRUgtNGYMJBz-yP-Newk12enadoIkXX70";
    // A new Fusion Table Layer
    var fTable = new google.maps.FusionTablesLayer();
    // Cache of school data
    var schoolData;

    // Sepcify "selected" counselor and app status
    var sCounselor = "";
    var sAppStatus = "Applied";

    /*
     * setSelectedCounselor(counselor)
     * 
     * This function sets counselor selected in the view to local
     * variable that data quieres can use.  
     * 
     *@param counselor The user selected couselor from drop down menu
     */
    var setSelectedCounselor = function(counselor) 
    {
        sCounselor = counselor;
    }

    /*
     * setSelectedAppStatus(appStat)
     * 
     * This function sets application status selected via the radio buttons
     * in the view to local variable that data quieres can use.  
     * 
     *@param appStat The user selected application status from three radio button choices
     */
    var setSelectedAppStatus = function(appStat) 
    {
        sAppStatus = appStat;
    }
    
    /*
     * getFusionTable()
     * 
     * This function is a simple getter method to retrieve the Google Fusion
     * Table with map layer and database info.   
     * 
     */
    var getFusionTable = function() 
    {
        return fTable;
    }

    /*
     * getSchoolData()
     * 
     * This function is a simple getter method to retrieve information from database. 
     * 
     */
    var getSchoolData = function()
    {
        return schoolData;
    }

    /*
     * selectCols()
     * 
     * This function updates application status on runtime with database infromation 
     * previously retrieved. 
     * 
     */
    var selectCols = function() 
    {
        return "HSCode, HSName, " + sAppStatus + ", Address, lat, lng, City, State";
    }

    /*
     * whereCond()
     * 
     * This function updates conselor on runtime with database infromation 
     * previously retrieved. 
     * 
     */
    var whereCond = function() 
    {
        return "Counselor = '" + sCounselor + "'";
    }

    /*
     * getLayer(cond)
     * 
     * This function querties a Google Fusion table and creates
     * a Fusion Table layer to apply to the specified map
     * 
     */
    var getLayer = function() 
    {
        // Need to evaluate before passing in
        var sel = selectCols();
        var cond = whereCond();

        fTable.setOptions({
            query: {
                select : sel,
                from : fTableId,
                where : cond
            },
            map : map,
            suppressInfoWindows : true,
        });

    }
   
    /*
     * getObject(cond)
     *
     * This function queries a Google Fusion table and returns
     * a JS object with the data to update the data table
     *
     */ 
    var getObject = function() 
    {
        var sql = "SELECT " + selectCols() + " FROM " + fTableId + 
                " WHERE " + whereCond() + " ORDER BY " + sAppStatus + " DESC";

        // Use jQuery get method to create an AJAX request to get
        // data from the Fusion Table
        $.get(queryUrl, { sql : sql, key : apikey }, function(data) 
        {
            schoolData = data.rows;
            dataSort();
            vm.updateView(map,schoolData);
        });

    };

    /*
     * setMap(gmap)
     * 
     * Sets a reference to the google map object
     * 
     * @param gmap the google map object to store
     */ 
    var setMap = function(gmap) 
    {
        map = gmap;
        
    };

    /*
     * setSchoolData(newList)
     * 
     * replaces the schoolData with a differently sorted list
     *
     * @param newList the new list order for the schoolData
     */ 
     var setSchoolData = function (newList)
     {
        schoolData = newList;
     };
     
    /*
     * dataSort()
     * 
     * This function takes the data in the data table and resorts it
     * to match the "filter by" requirements
     *
     */ 
    var dataSort = function() 
    {
        var sortBy = vm.getDataView();
        if(sortBy === "number"){
            //Sort using the number of apps, and use school name as the tie-breaker
            schoolData.sort(function (a, b) {
                if(b[2]-a[2] != 0)
                {
                    return (b[2] - a[2])
                }
                else
                {
                    if(a[1] < b[1]){return -1}
                    if(a[1] > b[1]){return 1;}
                    else {return 0};
                }
            })
            
            //Debug
            //for(var i = 0; i < schoolData.length; i++){
            //    console.log(schoolData[i][2]);
            //}
        }
        else{
            //use the concatenated string of the state, city and school name to get the proper sorting
            schoolData.sort(function (a, b) {
                var c = a[7]+a[6]+a[1];
                var d = b[7]+b[6]+b[1];
                //Debug
                //console.log(c);
                //console.log(d);
                if (c < d){return -1;}
                if (c > d){return 1;}
                else {return 0};
            })
            
            //Debug
            //for(var i = 0; i < schoolData.length; i++){
            //    console.log(schoolData[i][7] + " " + schoolData[i][6]);
            //}
        }
    };

    /*
     * queryData(cond)
     *
     * This function allows for cleaner code and compacts the number of methods other JavaScript
     * files and the view needs to interact with; it calls two other dataManager.js functions.  
     *
     */ 
    var queryData = function() 
    {
        getLayer();
        getObject(); 
    }

    // Any functions defined in this return statement are considered public
    // functions by RequireJS, and accessible through the namespace that
    // is attached to this module when loaded in other files.
    return {
        setMap : setMap,
        setSelectedCounselor : setSelectedCounselor,
        setSelectedAppStatus : setSelectedAppStatus,
        setSchoolData : setSchoolData,
        getFusionTable : getFusionTable,
        getSchoolData : getSchoolData,
        dataSort : dataSort,
        queryData : queryData,
    };

});

